<?php

namespace Tools\Rpc\Stream;

/**
 * Class Client
 */
class Client
{
    /** @var string $host */
    protected $host;

    /** @var int $port */
    protected $port;

    /** @var string $service */
    protected $service;

    /**
     * RpcClient constructor.
     * @param string $host
     * @param int $port
     * @param string $service
     */
    public function __construct(string $host, int $port, string $service)
    {
        $this->host = $host;
        $this->port = $port;
        $this->service = $service;
    }

    /**
     * @return string
     */
    public function getService(): string
    {
        return $this->service;
    }

    /**
     * @param string $service
     * @example $rpcClient->setService(App::class)
     */
    public function setService(string $service): void
    {
        $this->service = $service;
    }

    /**
     * @param string $method
     * @param array $parameters
     * @return false|string
     * @throws \Exception
     */
    public function __call(string $method, array $parameters)
    {
        $client = stream_socket_client("tcp://{$this->host}:{$this->port}", $errorCode, $errorMessage);
        if (false === $client) {
            throw new \Exception("{$errorCode} : {$errorMessage}" . PHP_EOL);
        }

        $requestData = json_encode([
            'service' => $this->service,
            'method' => $method,
            'parameters' => $parameters
        ]);

        fwrite($client, $requestData);

        $data = fread($client, 2048);

        fclose($client);

        return $data;
    }
}

